package halberd.filter;

import halberd.DataType;
import halberd.ImgFilter;
import halberd.data.ImgData;
import halberd.data.ImgDataFactory;
import halberd.utils.RGBUtils;

/**
 * 彩色电视
 * 
 * @author jiang
 *
 */
public class TVFilter implements ImgFilter {

	public ImgData process(ImgData input) {
		if (!canProcess(input)) {
			return null;
		}
		ImgData result = ImgDataFactory.createImgData(input.getWidth(), input.getHeight());
		tv(input.getDatas(), result.getDatas(), input.getWidth(), input.getHeight());
		result.copyType(input);
		return result;
	}

	private boolean canProcess(ImgData input) {
		if (input == null) {
			return false;
		}
		DataType dt = input.getDataType();
		if (dt == DataType.RGB) {
			return true;
		}
		if (dt == DataType.RGBA) {
			return true;
		}
		return false;
	}

	private void tv(int[][][] src, int[][][] dst, int w, int h) {
		for (int i = 0; i < w - 1; i += 2) {
			for (int j = 0; j < h - 1; j += 2) {
				int r = src[i][j][0];
				int g = src[i][j][1];
				int b = src[i][j][2];
				r += src[i + 1][j][0];
				g += src[i + 1][j][1];
				b += src[i + 1][j][2];
				r += src[i][j + 1][0];
				g += src[i][j + 1][1];
				b += src[i][j + 1][2];
				r += src[i + 1][j + 1][0];
				g += src[i + 1][j + 1][1];
				b += src[i + 1][j + 1][2];
				r = RGBUtils.clamp255((int) ((r + 0.5) / 4));
				g = RGBUtils.clamp255((int) ((g + 0.5) / 4));
				b = RGBUtils.clamp255((int) ((b + 0.5) / 4));
				dst[i][j][0] = r;
				dst[i][j][1] = 0;
				dst[i][j][2] = 0;

				dst[i + 1][j][0] = 0;
				dst[i + 1][j][1] = g;
				dst[i + 1][j][2] = 0;

				dst[i][j + 1][0] = 0;
				dst[i][j + 1][1] = 0;
				dst[i][j + 1][2] = b;

				dst[i + 1][j + 1][0] = r;
				dst[i + 1][j + 1][1] = g;
				dst[i + 1][j + 1][2] = b;
			}
		}
	}

}
